﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WxSDK.CacheSys;
using WxSDK.Common;

namespace WxSDK
{
    /// <summary>
    /// 继承此页面获取用户OpenID 
    /// <para>注意使用方法 , 继承此页面获取openid , 但是此页面仅作为跳转页面 , 不作为展示页面</para>
    /// <para>如果需要获取JSAPI相关信息 , 则不能再本页面调用相关方法 , 注意 :  本页面仅作为功能页面  禁止作为展示页使用</para>
    /// <para>默认 确认授权   注意  确认授权可以在用户未关注的情况下获取用户信息,静默授权则必须要关注才可以获取用户信息 </para> 
    /// <para>参数列表 mid scope </para>
    /// <para>mid 当前公众号信息 int类型 在webconfig中配置 </para>
    /// <para> scope 当前授权方式 默认是需要用户授权,不需要关注公众号即可获取用户相关信息    string类型 [snsapi_base,snsapi_userinfo]  </para>
    /// </summary>
    public class WeChats : System.Web.UI.Page
    {
        public WeChatModel.userInfo WeChat_UserInfo;
        public WxSDK.Model.wx_member WeChat_Member_Config;
        public Model.wx_member WeChat_Member;
        public int MemberId = WeChatConf.MemberId();
        public string Scope = "snsapi_base"; //WeChatConf.Scope(); //授权作用域  默认需要用户授权

        public WeChats()
        {
            this.Load += new EventHandler(WeChatPage_Load);
        }
#if false
        /// <summary>
        /// 获取MemberId 用户授权获取
        /// </summary>
        /// <returns></returns>
        public int GetMemberId()
        {
            //先从Session 中查看 再从QueryString 中查看
            //int.TryParse(WeChatCommon.ReadSession("mid").ToString(), out MemberId);
            int.TryParse(WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "mid") as string, out MemberId);
            if (MemberId > 0)
            {
                return MemberId;
            }
            else
            {
                int.TryParse(WeChatCommon.get_q("mid"), out MemberId);
                if (MemberId > 0)
                {
                    //WeChatCommon.WriteSession("mid", MemberId);
                    WeChatCache.Insert_NoAbsolute_Rank(CommFun.WeChatSessionIdentifierGet() + "mid", MemberId, WeChatMemory.CacheTimeOut, WeChatCache.GetRank(6));
                    WeChatCommon.WeChatLog(CommFun.WeChatSessionIdentifierGet() + " , " + WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "mid") as string + " , Cache");
                    return MemberId;
                }
                else
                {
                    return 0;
                }
            }
        }

        /// <summary>
        /// 获取授权作用域
        /// </summary>
        /// <returns></returns>
        public string GetScope()
        {
            //先从Session 中查看 再从QueryString 中查看
            //Scope = WeChatCommon.ReadSession("scope").ToString();
            Scope = WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "scope") as string;
            if (!string.IsNullOrEmpty(Scope))
            {
                return Scope;
            }
            else
            {
                Scope = WeChatCommon.get_q("scope").ToString();

                if (!string.IsNullOrEmpty(Scope))
                {
                    //WeChatCommon.WriteSession("scope", Scope);
                    WeChatCache.Insert_NoAbsolute(CommFun.WeChatSessionIdentifierGet() + "scope", Scope, WeChatMemory.CacheTimeOut);
                    return Scope;
                }
                else
                {
                    return "";
                }
            }
        }
#endif

        void WeChatPage_Load(object sender, EventArgs e)
        {
            //只有在入口每次都写入 , 保证唯一且持续可用
            CommFun.WeChatSessionIdentifierSet(Session.SessionID);

            if (string.IsNullOrEmpty(WeChatCommon.get_q("code")))
            {
                if (!string.IsNullOrEmpty(WeChat_Pub.get_q("from")))
                {
                    WeChatCache.Insert_NoSliding(CommFun.WeChatSessionIdentifierGet() + "_referrer", WeChat_Pub.get_q("from"), 20);
                }
                else {
                    WeChatCache.Insert_NoSliding(CommFun.WeChatSessionIdentifierGet() + "_referrer", "noredirect", 20);
                }
            }

            //MemberId = ;
            //int.TryParse(CommFun.GetQueryString("mid"), out MemberId);
            if (MemberId <= 0)
            {
                //检查缓存 , 缓存里面没有就报错出去
                object mid = WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "_memberid");
                if (mid == null)
                {
                    Response.Write("MemberId 参数(mid)错误 , 请检查mid是否正确");
                    Response.End();
                }
                else
                {
                    MemberId = Convert.ToInt32(mid);
                }
            }
            else
            {
                //存缓存
                WeChatCache.Insert_NoAbsolute_Rank(CommFun.WeChatSessionIdentifierGet() + "_memberid", MemberId, 7200, System.Web.Caching.CacheItemPriority.NotRemovable);
            }
            
            //Scope = GetScope();
            //WeChatCommon.WeChatLog("Scope : " + Scope);
            WeChat_Member = WeChatMemory.MemberInfo(MemberId);
            WeChat_Member_Config = WeChatMemory.MemberInfo(WeChat_Member.Id);
            //WeChatCommon.WeChatLog(WeChatCommon.ReadSession("wx_user").ToString());
            if (WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "_wx_user")==null)
            {
                //WeChatApi wxapi = new WeChatApi();
                if (string.IsNullOrEmpty(WeChatCommon.get_q("code")))
                {
                    Response.Redirect(string.Format(WeChat_Url.GetCode, WeChat_Member.APPID, System.Web.HttpContext.Current.Server.UrlEncode(WeChat_Member.REDIRECT_URL), Scope, MemberId));
                }
                else
                {
                    string code = WeChatCommon.get_q("code");
                    string result = "";
                    if (Scope == "snsapi_userinfo") //需要确认授权
                    {
                        //如果是确认授权, 需要重新获取用户信息 需要重新这里逻辑...
                        //先通过code获取AccessToken,然后用AccessToken和Openid获取用户信息
                        result = WeChatCommon.HttpGet(string.Format(WeChat_Url.UserAuthAccessToken, WeChat_Member.APPID, WeChat_Member.APPSECRET, code));
                        WeChatModel.authAccessToken authaccesstoken = Newtonsoft.Json.JsonConvert.DeserializeObject<WeChatModel.authAccessToken>(result);
                        string accessToken = WeChatConf.AccessToken(MemberId);
                        result = WeChatCommon.HttpGet(string.Format(WeChat_Url.GetUserInfo, accessToken, authaccesstoken.openid));
                        //result = WeChatCommon.HttpGet(string.Format(WeChat_Url.UserAuthGetUserInfo, accessToken, authaccesstoken.openid));
                        //result = WeChatCommon.HttpGet(string.Format(WeChat_Url.UserAuthGetUserInfo, authaccesstoken.access_token, authaccesstoken.openid));
                        WeChat_UserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeChatModel.userInfo>(result);
                    }
                    if (Scope == "snsapi_base") //静默授权
                    {
                        result = WeChatCommon.HttpGet(string.Format(WeChat_Url.GetUserInfo, WeChatApi.GetAccessToken(MemberId), WeChatApi.getOpenid(MemberId, code)));
                        WeChat_UserInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeChatModel.userInfo>(result);
                    }
                    WeChatCache.Insert_NoAbsolute(CommFun.WeChatSessionIdentifierGet() + "_wx_user", WeChat_UserInfo, WeChatMemory.CacheTimeOut);
                    WxRedirect();
                }
            }
            else
            {
                WeChat_UserInfo = (WeChatModel.userInfo)WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "_wx_user");
                WxRedirect();
            }
            
        }

        void WxRedirect() {
            if (WeChat_UserInfo != null)
            {
                string referrer = WeChatCache.GetValue(CommFun.WeChatSessionIdentifierGet() + "_referrer") as string;
                referrer = WxSDK.Common.CommFun.UrlDecode(referrer);
                if (referrer == "noredirect")
                {
                    WeChatCache.Del(CommFun.WeChatSessionIdentifierGet() + "_referrer");
                }
                else if (!string.IsNullOrEmpty(referrer))
                {
                    WeChatCache.Del(CommFun.WeChatSessionIdentifierGet() + "_referrer");
                    Response.Redirect(referrer);
                }
                else
                {
                    if (!string.IsNullOrEmpty(WeChat_Member_Config.DefaultRedirect))
                    {
                        Response.Redirect(WeChat_Member_Config.DefaultRedirect);
                    }
                }
            }
        }


        

    }
}
